package evaluatetask

import (
	"ZHONGYIHANGYAN/bean/dbModel"
	"ZHONGYIHANGYAN/bean/request"
	"ZHONGYIHANGYAN/bean/response"
	commUtils "ZHONGYIHANGYAN/commUtils"
	"context"
	"fmt"
	"math"
	"sort"
	"time"
	cfg "ZHONGYIHANGYAN/cfg"
	"gorm.io/gorm"
)

// 辅助函数：安全地格式化时间指针
func formatTimePtr(t *time.Time) string {
	if t == nil {
		return ""
	}
	return t.Format("2006-01-02 15:04:05")
}

// 辅助函数：计算中位数
func calculateMedian(scores []float64) float64 {
	if len(scores) == 0 {
		return 0
	}
	
	// 复制切片并排序
	sortedScores := make([]float64, len(scores))
	copy(sortedScores, scores)
	sort.Float64s(sortedScores)
	
	n := len(sortedScores)
	if n%2 == 0 {
		// 偶数个数，取中间两个数的平均值
		return (sortedScores[n/2-1] + sortedScores[n/2]) / 2
	} else {
		// 奇数个数，取中间的数
		return sortedScores[n/2]
	}
}

// 辅助函数：计算标准差
func calculateStandardDeviation(scores []float64) float64 {
	if len(scores) == 0 {
		return 0
	}
	
	// 计算平均值
	var sum float64
	for _, score := range scores {
		sum += score
	}
	mean := sum / float64(len(scores))
	
	// 计算方差
	var variance float64
	for _, score := range scores {
		diff := score - mean
		variance += diff * diff
	}
	variance = variance / float64(len(scores))
	
	// 返回标准差（方差的平方根）
	return math.Sqrt(variance)
}

// 启动任务监控
func (manage *EvaluateTaskManage) startTaskMonitor(taskId string) {
	// 检查是否已经在监控中
	if monitor, exists := manage.monitors.Load(taskId); exists {
		if taskMonitor := monitor.(*TaskMonitor); taskMonitor.IsActive {
			fmt.Printf("📊 任务 %s 已在监控中，跳过启动\n", taskId)
			return
		}
	}
	
	// 创建新的监控
	ctx, cancel := context.WithCancel(context.Background())
	monitor := &TaskMonitor{
		TaskId:   taskId,
		Cancel:   cancel,
		IsActive: true,
	}
	
	manage.monitors.Store(taskId, monitor)
	
	// 启动监控goroutine
	go func() {
		fmt.Printf("🚀 启动任务监控: %s\n", taskId)
		ticker := time.NewTicker(10 * time.Second) // 每10秒检查一次
		defer ticker.Stop()
		
		for {
			select {
			case <-ctx.Done():
				fmt.Printf("🛑 停止任务监控: %s\n", taskId)
				return
			case <-ticker.C:
				// 执行自动终止检查
				if terminated := manage.checkAndAutoTerminateTask(taskId); terminated {
					// 任务已自动终止，停止监控
					manage.stopTaskMonitor(taskId)
					return
				}
			}
		}
	}()
}

// 停止任务监控
func (manage *EvaluateTaskManage) stopTaskMonitor(taskId string) {
	if monitor, exists := manage.monitors.Load(taskId); exists {
		if taskMonitor := monitor.(*TaskMonitor); taskMonitor.IsActive {
			taskMonitor.Cancel()
			taskMonitor.IsActive = false
			fmt.Printf("⏹️ 已停止任务监控: %s\n", taskId)
		}
		manage.monitors.Delete(taskId)
	}
}

// 检查并自动终止达到计划时长的任务
func (manage *EvaluateTaskManage) checkAndAutoTerminateTask(taskId string) bool {
	db := manage.DataBase.DB()
	currentTime := time.Now().Local()
	
	var task dbModel.EvaluateTask
	if err := db.Where("id = ?", taskId).First(&task).Error; err != nil {
		fmt.Printf("⚠️ 监控检查失败，任务ID: %s, 错误: %v\n", taskId, err)
		return false // 任务不存在或查询失败
	}
	
	// 只处理未终止且有计划时长的任务
	if task.ExecStatus == 3 {
		fmt.Printf("📋 任务 %s 已终止，无需检查\n", taskId)
		return true // 任务已终止，返回true停止监控
	}
	
	if task.PlanDuration <= 0 {
		fmt.Printf("📋 任务 %s 无计划时长，无需检查\n", taskId)
		return false // 无计划时长，继续监控
	}
	
	var currentRealDuration int = task.RealDuration
	
	// 如果当前状态是进行中，需要加上从LastStartTime到现在的时间
	if task.ExecStatus == 1 && task.LastStartTime != nil {
		durationFromLastStart := int(currentTime.Sub(*task.LastStartTime).Seconds())
		if durationFromLastStart > 0 {
			currentRealDuration += durationFromLastStart
		}
	}
	
	// 检查是否需要自动终止
	if currentRealDuration >= task.PlanDuration {
		fmt.Printf("🤖 自动终止检查：任务 %s 达到计划时长，自动终止\n", taskId)
		fmt.Printf("计划时长: %d秒, 实际时长: %d秒\n", task.PlanDuration, currentRealDuration)
		
		updateData := map[string]interface{}{
			"exec_status": 3, // 终止状态
			"end_time":    &currentTime,
		}
		
		// 如果之前是进行中状态，需要累加最后一段时间到RealDuration
		if task.ExecStatus == 1 && task.LastStartTime != nil {
			durationFromLastStart := int(currentTime.Sub(*task.LastStartTime).Seconds())
			if durationFromLastStart > 0 {
				newRealDuration := task.RealDuration + durationFromLastStart
				updateData["real_duration"] = newRealDuration
				fmt.Printf("累加最后一段时间: %d秒, 最终时长: %d秒\n", durationFromLastStart, newRealDuration)
			}
		}
		
		// 执行自动终止更新
		result := db.Model(&dbModel.EvaluateTask{}).Where("id = ?", taskId).Updates(updateData)
		if result.Error != nil {
			fmt.Printf("❌ 自动终止失败: %v\n", result.Error)
			return false
		}
		
		fmt.Printf("✅ 任务 %s 已自动终止\n", taskId)
		
		// 启动6分钟倒计时
		manage.startFinalScoreCountdown(taskId)
		
		return true // 任务已终止，停止监控
	} else {
		remainingTime := task.PlanDuration - currentRealDuration
		fmt.Printf("⏰ 任务 %s 剩余时间: %d秒\n", taskId, remainingTime)
	}
	
	return false // 任务未终止，继续监控
}

// 启动6分钟倒计时，倒计时结束后计算最终评分
func (manage *EvaluateTaskManage) startFinalScoreCountdown(taskId string) {
	// 检查是否已经在倒计时中
	if countdown, exists := manage.countdowns.Load(taskId); exists {
		if finalCountdown := countdown.(*FinalScoreCountdown); finalCountdown.IsActive {
			fmt.Printf("⏱️ 任务 %s 已在倒计时中，跳过启动\n", taskId)
			return
		}
	}
	
	// 创建新的倒计时
	ctx, cancel := context.WithCancel(context.Background())
	countdown := &FinalScoreCountdown{
		TaskId:   taskId,
		Cancel:   cancel,
		IsActive: true,
	}
	
	manage.countdowns.Store(taskId, countdown)
	
	// 启动倒计时goroutine
	go func() {
		fmt.Printf("⏱️ 启动6分钟倒计时: %s\n", taskId)
		
		// 6分钟倒计时
		countdownDuration := time.Duration(cfg.Sys.FinalScoreCountdown) * time.Second
		timer := time.NewTimer(countdownDuration)
		defer timer.Stop()
		
		// 定期输出倒计时进度
		progressTicker := time.NewTicker(1 * time.Minute) // 每分钟输出一次进度
		defer progressTicker.Stop()
		
		startTime := time.Now()
		
		for {
			select {
			case <-ctx.Done():
				fmt.Printf("🛑 倒计时已取消: %s\n", taskId)
				return
			case <-progressTicker.C:
				elapsed := time.Since(startTime)
				remaining := countdownDuration - elapsed
				if remaining > 0 {
					fmt.Printf("⏱️ 任务 %s 倒计时进度: 剩余 %.0f 分钟\n", taskId, remaining.Minutes())
				}
			case <-timer.C:
				fmt.Printf("⏰ 倒计时结束，开始计算最终评分: %s\n", taskId)
				
				// 倒计时结束，计算最终评分
				if err := manage.calculateFinalScore(taskId); err != nil {
					fmt.Printf("❌ 计算最终评分失败，任务ID: %s, 错误: %v\n", taskId, err)
				} else {
					fmt.Printf("✅ 最终评分计算完成: %s\n", taskId)
				}
				
				// 清理倒计时
				manage.stopFinalScoreCountdown(taskId)
				return
			}
		}
	}()
}

// 停止6分钟倒计时
func (manage *EvaluateTaskManage) stopFinalScoreCountdown(taskId string) {
	if countdown, exists := manage.countdowns.Load(taskId); exists {
		if finalCountdown := countdown.(*FinalScoreCountdown); finalCountdown.IsActive {
			finalCountdown.Cancel()
			finalCountdown.IsActive = false
			fmt.Printf("⏹️ 已停止倒计时: %s\n", taskId)
		}
		manage.countdowns.Delete(taskId)
	}
}

// 计算任务的最终评分
func (manage *EvaluateTaskManage) calculateFinalScore(taskId string) error {
	db := manage.DataBase.DB()
	
	fmt.Printf("🧮 开始计算最终评分，任务ID: %s\n", taskId)
	
	// 1. 查询所有专家的总分记录（IsTotalScore=true）
	var expertTotalScores []dbModel.EvaluateResult
	if err := db.Where("task_id = ? AND is_total_score = ?", taskId, true).Find(&expertTotalScores).Error; err != nil {
		return fmt.Errorf("查询专家总分记录失败: %v", err)
	}
	
	fmt.Printf("📊 找到 %d 个专家的总分记录\n", len(expertTotalScores))
	
	if len(expertTotalScores) == 0 {
		fmt.Printf("⚠️ 未找到任何专家总分记录，跳过最终评分计算\n")
		return nil
	}
	
	// 2. 计算所有专家的总分和
	var totalAverageScore float64 = 0
	var totalAbsoluteScore float64 = 0
	
	expertScoreDetails := make(map[string][]float64) // 专家ID -> [averageScore, absoluteScore]
	
	for _, expertScore := range expertTotalScores {
		totalAverageScore += expertScore.AverageScore
		totalAbsoluteScore += expertScore.AbsoluteScore
		expertScoreDetails[expertScore.ExpertId] = []float64{expertScore.AverageScore, expertScore.AbsoluteScore}
		
		fmt.Printf("专家 %s: AverageScore=%.2f, AbsoluteScore=%.2f\n", 
			expertScore.ExpertId, expertScore.AverageScore, expertScore.AbsoluteScore)
	}
	
	fmt.Printf("🎯 最终总分: AverageScore=%.2f, AbsoluteScore=%.2f\n", totalAverageScore, totalAbsoluteScore)
	
	// 3. 更新evaluate_task表中的最终评分
	updateData := map[string]interface{}{
		"total_average_score":          totalAverageScore,
		"total_absolute_score": totalAbsoluteScore,
	}
	
	result := db.Model(&dbModel.EvaluateTask{}).Where("id = ?", taskId).Updates(updateData)
	if result.Error != nil {
		return fmt.Errorf("更新最终评分失败: %v", result.Error)
	}
	
	if result.RowsAffected == 0 {
		return fmt.Errorf("更新失败，未找到ID为 %s 的任务", taskId)
	}
	
	fmt.Printf("💾 最终评分已保存到数据库\n")
	fmt.Printf("===== 最终评分计算完成 =====\n")
	fmt.Printf("任务ID: %s\n", taskId)
	fmt.Printf("参与专家数: %d\n", len(expertTotalScores))
	fmt.Printf("最终AverageScore: %.2f\n", totalAverageScore)
	fmt.Printf("最终AbsoluteScore: %.2f\n", totalAbsoluteScore)
	fmt.Printf("=================================\n\n")
	
	return nil
}

// 重新计算评价任务的指标统计结果
func (manage *EvaluateTaskManage) recalculateTaskTotalResults(tx *gorm.DB, taskId string, templateId string) error {
	fmt.Printf("🧮 开始重新计算任务指标统计结果，任务ID: %s\n", taskId)
	
	// 1. 查询该任务所有专家的评价结果（排除总分记录）
	var evaluateResults []dbModel.EvaluateResult
	if err := tx.Where("task_id = ? AND is_total_score = ?", taskId, false).Find(&evaluateResults).Error; err != nil {
		return fmt.Errorf("查询评价结果失败: %v", err)
	}
	
	fmt.Printf("📊 找到 %d 条指标评价记录\n", len(evaluateResults))
	
	if len(evaluateResults) == 0 {
		fmt.Printf("⚠️ 未找到指标评价记录，跳过统计计算\n")
		return nil
	}
	
	// 2. 按指标ID分组统计
	quotaStatsMap := make(map[string]struct {
		QuotaId        string
		QuotaName      string
		AverageScores  []float64
		AbsoluteScores []float64
	})
	
	for _, result := range evaluateResults {
		if stats, exists := quotaStatsMap[result.QuotaId]; exists {
			stats.AverageScores = append(stats.AverageScores, result.AverageScore)
			stats.AbsoluteScores = append(stats.AbsoluteScores, result.AbsoluteScore)
			quotaStatsMap[result.QuotaId] = stats
		} else {
			quotaStatsMap[result.QuotaId] = struct {
				QuotaId        string
				QuotaName      string
				AverageScores  []float64
				AbsoluteScores []float64
			}{
				QuotaId:        result.QuotaId,
				QuotaName:      result.QuotaName,
				AverageScores:  []float64{result.AverageScore},
				AbsoluteScores: []float64{result.AbsoluteScore},
			}
		}
	}
	
	// 3. 删除该任务原有的统计结果
	if err := tx.Where("task_id = ?", taskId).Delete(&dbModel.EvaluateTotalResult{}).Error; err != nil {
		return fmt.Errorf("删除原有统计结果失败: %v", err)
	}

	// 计算任务总分值
	var taskAverageScore, taskAbsoluteScore float64 = 0, 0
	
	// 4. 计算新的统计结果并插入
	var totalResults []dbModel.EvaluateTotalResult
	for quotaId, stats := range quotaStatsMap {
		// 计算平均值
		var averageSum, absoluteSum float64
		for _, score := range stats.AverageScores {
			averageSum += score
		}
		for _, score := range stats.AbsoluteScores {
			absoluteSum += score
		}
		
		avgScore := averageSum / float64(len(stats.AverageScores))
		avgAbsoluteScore := absoluteSum / float64(len(stats.AbsoluteScores))
		
		// 计算中位数
		medianScore := calculateMedian(stats.AverageScores)
		
		// 计算标准差
		standardDeviationScore := calculateStandardDeviation(stats.AverageScores)
		
		totalResult := dbModel.EvaluateTotalResult{
			Id:            commUtils.GenUUID(),
			TaskId:        taskId,
			TemplateId:    templateId,
			QuotaId:       quotaId,
			QuotaName:     stats.QuotaName,
			AverageScore:  avgScore,
			MedianScore:   medianScore,
			AbsoluteScore: avgAbsoluteScore,
			StandardDeviationScore: standardDeviationScore,
		}
		
		totalResults = append(totalResults, totalResult)
		
		fmt.Printf("指标 %s (%s): 专家数=%d, 平均分=%.2f, 中位分=%.2f, 标准差=%.2f, 绝对分=%.2f\n",
			stats.QuotaName, quotaId, len(stats.AverageScores), avgScore, medianScore, standardDeviationScore, avgAbsoluteScore)

		taskAverageScore += avgScore
		taskAbsoluteScore += avgAbsoluteScore
	}
	
	// 5. 批量插入统计结果
	if len(totalResults) > 0 {
		if err := tx.CreateInBatches(totalResults, 100).Error; err != nil {
			return fmt.Errorf("创建统计结果失败: %v", err)
		}
		fmt.Printf("✅ 成功创建 %d 条指标统计结果\n", len(totalResults))
	}

	
	// 更新任务表中的分值
	updateData := map[string]interface{}{
    	"total_absolute_score": taskAverageScore,
    	"total_score":          taskAverageScore,
	}

	if err := tx.Model(&dbModel.EvaluateTask{}).Where("id = ?", taskId).Updates(updateData).Error; err != nil {
    	tx.Rollback()
    	return fmt.Errorf("更新任务分值失败: %v", err)
	}
	
	fmt.Printf("🎯 任务指标统计计算完成\n")
	return nil
}

// 获取评价任务列表
func (manage *EvaluateTaskManage) GetEvaluateTaskList(query *request.GetEvaluateTaskListQuery) (response.PageData, error) {
	pageData := response.PageData{}

	db := manage.DataBase.DB()
	tx := db.Model(&dbModel.EvaluateTask{})

	// 根据任务名称模糊查询
	if query.Name != "" {
		tx = tx.Where("name LIKE ?", "%"+query.Name+"%")
	}
	
	// 根据执行状态筛选
	if query.ExecStatus != nil {
		tx = tx.Where("exec_status = ?", query.ExecStatus)
	}
	
	// 根据资源名称模糊查询
	if query.ResourceName != nil && *query.ResourceName != "" {
		tx = tx.Where("resource_name LIKE ?", "%"+*query.ResourceName+"%")
	}
	
	// 根据开始时间筛选 (筛选开始时间晚于或等于指定时间的任务)
	if query.StartTime != nil && *query.StartTime != "" {
		// 解析时间字符串
		if startTime, err := time.Parse("2006-01-02 15:04:05", *query.StartTime); err == nil {
			tx = tx.Where("start_time >= ?", startTime)
		}
	}
	
	// 根据结束时间筛选 (筛选结束时间早于或等于指定时间的任务)
	if query.EndTime != nil && *query.EndTime != "" {
		// 解析时间字符串
		if endTime, err := time.Parse("2006-01-02 15:04:05", *query.EndTime); err == nil {
			tx = tx.Where("end_time <= ?", endTime)
		}
	}
	
	// 根据专家ID列表筛选 (通过关联表查询)
	if len(query.ExpertIds) > 0 {
		// 子查询：获取包含指定专家的任务ID列表
		subQuery := db.Model(&dbModel.ExpertAndEvaluateTaskRelationship{}).
			Select("task_id").
			Where("expert_id IN ?", query.ExpertIds)
		tx = tx.Where("id IN (?)", subQuery)
	}

	// 根据综合得分筛选
	if query.MinScore != nil {
		tx.Where("total_absolute_score >= ?", *query.MinScore)
	}
	if query.MaxScore != nil {
		tx.Where("total_absolute_score <= ?", *query.MaxScore)
	}

	// 获取总记录数
	var total int64
	if err := tx.Count(&total).Error; err != nil {
		return pageData, err
	}
	if total == 0 {
		pageData.List = []interface{}{}
		return pageData, nil
	}

	// 分页查询
	currentPage := query.CurrentPage
	numPerPage := query.NumPerPage
	if currentPage <= 0 {
		currentPage = 1
	}
	if numPerPage <= 0 {
		numPerPage = 50
	}
	offset := (currentPage - 1) * numPerPage
	tx = tx.Order("create_time DESC").Limit(numPerPage).Offset(offset)

	var taskList []dbModel.EvaluateTask
	if err := tx.Find(&taskList).Error; err != nil {
		return pageData, err
	}

	var taskIds []string
	for _, task := range taskList {
		taskIds = append(taskIds, task.Id)
	}

	// 批量获取专家与评价任务关系记录
	var expertAndEvaluateTaskRelationshipList []dbModel.ExpertAndEvaluateTaskRelationship
	if len(taskIds) > 0 {
		db.Where("task_id IN ?", taskIds).Find(&expertAndEvaluateTaskRelationshipList)
	}

	// 构建任务ID到专家ID的映射
	expertIdMap := make(map[string][]string)
	allExpertIdsSet := make(map[string]bool)
	for _, relationship := range expertAndEvaluateTaskRelationshipList {
		expertIdMap[relationship.TaskId] = append(expertIdMap[relationship.TaskId], relationship.ExpertId)
		allExpertIdsSet[relationship.ExpertId] = true
	}

	// 将去重后的专家ID转为切片
	var allExpertIds []string
	for expertId := range allExpertIdsSet {
		allExpertIds = append(allExpertIds, expertId)
	}

	// 批量查询所有专家用户信息
	expertUserMap := make(map[string]response.Expert)
	if len(allExpertIds) > 0 {
		var users []dbModel.User
		if err := db.Where("id IN ?", allExpertIds).Find(&users).Error; err != nil {
			return pageData, fmt.Errorf("查询专家用户信息失败: %v", err)
		}
		for _, user := range users {
			expertUserMap[user.Id] = response.Expert{
				Id:       user.Id,
				Username: user.UserName,
				UserCode: user.UserCode,
			}
		}
	}

	// 转换为响应格式
	var responseList []response.GetEvaluateTaskListResponse
	for _, task := range taskList {
		// 从映射中获取专家ID列表
		expertIds := expertIdMap[task.Id]
		if expertIds == nil {
			expertIds = []string{}
		}

		// 构建专家列表
		var expertList []response.Expert
		for _, expertId := range expertIds {
			if expert, exists := expertUserMap[expertId]; exists {
				expertList = append(expertList, expert)
			}
		}

		responseItem := response.GetEvaluateTaskListResponse{
			Id:            task.Id,
			Name:          task.Name,
			Desc:          task.Desc,
			ResourceType:  task.ResourceType,
			ResourceId:    task.ResourceId,
			ResourceName:  task.ResourceName,
			TemplateId:    task.TemplateId,
			TemplateName:  task.TemplateName,
			PlanDuration:  task.PlanDuration,
			RealDuration:  task.RealDuration,
			StartTime:     formatTimePtr(task.StartTime),
			EndTime:       formatTimePtr(task.EndTime),
			LastStartTime: formatTimePtr(task.LastStartTime),
			ExecStatus:    task.ExecStatus,
			SegmentTime:   task.SegmentTime,
			ExpertList:    expertList,
			CreateTime:    task.CreateTime.Format("2006-01-02 15:04:05"),
			UpdateTime:    task.UpdateTime.Format("2006-01-02 15:04:05"),
			TotalScore:    task.TotalScore,
			TotalAbsoluteScore: task.TotalAbsoluteScore,
		}
		responseList = append(responseList, responseItem)
	}

	pageData.CurrentPage = currentPage
	pageData.NumPerPage = numPerPage
	pageData.TotalCount = int(total)
	pageData.TotalPages = (pageData.TotalCount + numPerPage - 1) / numPerPage
	pageData.List = responseList

	return pageData, nil
}

// 添加或修改评价任务
func (manage *EvaluateTaskManage) AddOrUpdateEvaluateTask(task *request.AddOrUpdateEvaluateTaskQuery) (string, error) {
	fmt.Printf("===== 开始添加或修改评价任务 =====\n")
	fmt.Printf("操作类型: %s\n", map[bool]string{true: "修改", false: "新增"}[task.Id != ""])
	fmt.Printf("任务ID: %s\n", task.Id)
	fmt.Printf("任务名称: %s\n", task.Name)
	fmt.Printf("执行状态: %d\n", task.ExecStatus)
	fmt.Printf("专家数量: %d\n", len(task.ExpertIds))

	db := manage.DataBase.DB()

	// 开启事务确保数据一致性
	tx := db.Begin()
	if tx.Error != nil {
		return "", fmt.Errorf("开启事务失败: %v", tx.Error)
	}
	fmt.Println("事务已开启")

	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
			fmt.Printf("发生panic，事务已回滚: %v\n", r)
		}
	}()

	isUpdate := task.Id != ""

	var taskId string
	currentTime := time.Now().Local() // 确保使用本地时区

	if !isUpdate {
		// 新增评价任务
		taskId = commUtils.GenUUID()
		fmt.Printf("生成新任务ID: %s\n", taskId)

		taskToCreate := dbModel.EvaluateTask{
			Id:           taskId,
			Name:         task.Name,
			Desc:         task.Desc,
			ResourceType: task.ResourceType,
			ResourceId:   task.ResourceId,
			ResourceName: task.ResourceName,
			TemplateId:   task.TemplateId,
			TemplateName: task.TemplateName,
			PlanDuration: task.PlanDuration,
			SegmentTime:  task.SegmentTime,
			ExecStatus:   task.ExecStatus, // 默认状态：0-未开始
		}

		// 如果状态为1（开始评价），设置开始时间
		if task.ExecStatus == 1 {
			taskToCreate.StartTime = &currentTime
			taskToCreate.LastStartTime = &currentTime
			fmt.Printf("设置开始时间: %s (Unix: %d, 时区: %s)\n",
				currentTime.Format("2006-01-02 15:04:05"),
				currentTime.Unix(),
				currentTime.Location())
		}

		fmt.Println("开始创建评价任务...")
		if err := tx.Create(&taskToCreate).Error; err != nil {
			tx.Rollback()
			fmt.Printf("创建评价任务失败: %v\n", err)
			return "", fmt.Errorf("创建评价任务失败: %v", err)
		}
		fmt.Println("评价任务创建成功")
	} else {
		// 修改评价任务
		taskId = task.Id
		fmt.Printf("修改现有任务，任务ID: %s\n", taskId)

		// 如果修改后的状态为1，需要先查询当前任务信息来处理时间字段
		var currentTask dbModel.EvaluateTask
		if task.ExecStatus == 1 {
			fmt.Println("查询当前任务信息（用于时间字段处理）...")
			if err := tx.Where("id = ?", taskId).First(&currentTask).Error; err != nil {
				tx.Rollback()
				if err.Error() == "record not found" {
					fmt.Printf("任务不存在: %s\n", taskId)
					return "", fmt.Errorf("评价任务不存在")
				}
				fmt.Printf("查询任务失败: %v\n", err)
				return "", fmt.Errorf("查询评价任务失败: %v", err)
			}
			fmt.Println("当前任务信息查询成功")
		}

		updateData := map[string]interface{}{
			"name":          task.Name,
			"desc":          task.Desc,
			"resource_type": task.ResourceType,
			"resource_id":   task.ResourceId,
			"resource_name": task.ResourceName,
			"template_id":   task.TemplateId,
			"template_name": task.TemplateName,
			"plan_duration": task.PlanDuration,
			"segment_time":  task.SegmentTime,
			"exec_status":   task.ExecStatus,
		}

		// 如果状态为1（开始评价），设置时间字段
		if task.ExecStatus == 1 {
			// StartTime如果已经有值就不更新，没有值就设置为当前时间
			if currentTask.StartTime == nil {
				updateData["start_time"] = &currentTime
				fmt.Printf("设置StartTime: %s (Unix: %d, 时区: %s)\n",
					currentTime.Format("2006-01-02 15:04:05"),
					currentTime.Unix(),
					currentTime.Location())
			} else {
				fmt.Printf("StartTime已存在，不更新: %s (Unix: %d, 时区: %s)\n",
					currentTask.StartTime.Format("2006-01-02 15:04:05"),
					currentTask.StartTime.Unix(),
					currentTask.StartTime.Location())
			}
			// LastStartTime每次都更新
			updateData["last_start_time"] = &currentTime
			fmt.Printf("更新LastStartTime: %s (Unix: %d, 时区: %s)\n",
				currentTime.Format("2006-01-02 15:04:05"),
				currentTime.Unix(),
				currentTime.Location())
		}

		fmt.Println("开始更新评价任务...")
		result := tx.Model(&dbModel.EvaluateTask{}).Where("id = ?", taskId).Updates(updateData)
		if result.Error != nil {
			tx.Rollback()
			fmt.Printf("更新评价任务失败: %v\n", result.Error)
			return "", fmt.Errorf("更新评价任务失败: %v", result.Error)
		}
		if result.RowsAffected == 0 {
			tx.Rollback()
			fmt.Printf("更新失败，未找到记录: %s\n", taskId)
			return "", fmt.Errorf("更新评价任务失败：ID 为 %s 的记录未找到", taskId)
		}
		fmt.Printf("评价任务更新成功，受影响行数: %d\n", result.RowsAffected)
	}

	// 处理专家与评价任务关系记录
	fmt.Println("开始处理专家关系记录...")
	if isUpdate {
		// 修改任务时，先删除原有的专家关系记录
		fmt.Println("删除原有专家关系记录...")
		if err := tx.Where("task_id = ?", taskId).Delete(&dbModel.ExpertAndEvaluateTaskRelationship{}).Error; err != nil {
			tx.Rollback()
			fmt.Printf("删除原有专家关系记录失败: %v\n", err)
			return "", fmt.Errorf("删除原有专家关系记录失败: %v", err)
		}
		fmt.Println("原有专家关系记录删除成功")
	}

	// 创建新的专家与评价任务关系记录
	if len(task.ExpertIds) > 0 {
		fmt.Printf("创建新的专家关系记录，专家数量: %d\n", len(task.ExpertIds))
		var expertList []dbModel.ExpertAndEvaluateTaskRelationship
		for _, expertId := range task.ExpertIds {
			expert := dbModel.ExpertAndEvaluateTaskRelationship{
				Id:       commUtils.GenUUID(),
				TaskId:   taskId,
				ExpertId: expertId,
			}
			expertList = append(expertList, expert)
		}
		if err := tx.CreateInBatches(expertList, 100).Error; err != nil {
			tx.Rollback()
			fmt.Printf("创建专家与评价任务关系记录失败: %v\n", err)
			return "", fmt.Errorf("创建专家与评价任务关系记录失败: %v", err)
		}
		fmt.Println("专家关系记录创建成功")
	} else {
		fmt.Println("无专家关系记录需要创建")
	}

	// 提交事务
	fmt.Println("开始提交事务...")
	if err := tx.Commit().Error; err != nil {
		fmt.Printf("提交事务失败: %v\n", err)
		return "", fmt.Errorf("提交事务失败: %v", err)
	}

	fmt.Printf("===== 操作完成 =====\n")
	fmt.Printf("任务ID: %s\n", taskId)
	fmt.Printf("事务已成功提交\n")

	// 根据任务状态管理监控和倒计时
	if task.ExecStatus == 1 && task.PlanDuration > 0 {
		// 状态为进行中且有计划时长，启动监控，停止倒计时
		manage.startTaskMonitor(taskId)
		manage.stopFinalScoreCountdown(taskId)
	} else if task.ExecStatus == 3 {
		// 状态为终止，停止监控，启动倒计时
		manage.stopTaskMonitor(taskId)
		manage.startFinalScoreCountdown(taskId)
	} else {
		// 其他状态，停止监控和倒计时
		manage.stopTaskMonitor(taskId)
		manage.stopFinalScoreCountdown(taskId)
	}

	fmt.Printf("监控管理完成\n\n")

	return taskId, nil
}

// 删除评价任务
func (manage *EvaluateTaskManage) DeleteEvaluateTask(evaluateTaskIds []string) error {
	if len(evaluateTaskIds) == 0 {
		return nil
	}

	db := manage.DataBase.DB()

	// 开启事务确保数据一致性
	tx := db.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()

	// 删除评价任务记录
	result := tx.Where("id IN ?", evaluateTaskIds).Delete(&dbModel.EvaluateTask{})
	if result.Error != nil {
		tx.Rollback()
		return fmt.Errorf("删除评价任务失败: %v", result.Error)
	}
	if result.RowsAffected == 0 {
		tx.Rollback()
		return fmt.Errorf("没有找到要删除的评价任务记录，ID列表可能无效或记录已被删除")
	}

	// 提交事务
	if err := tx.Commit().Error; err != nil {
		return fmt.Errorf("提交事务失败: %v", err)
	}

	// 停止所有被删除任务的监控和倒计时
	for _, taskId := range evaluateTaskIds {
		manage.stopTaskMonitor(taskId)
		manage.stopFinalScoreCountdown(taskId)
	}

	return nil
}

// 获取评价任务详情
func (manage *EvaluateTaskManage) GetEvaluateTaskDetail(query *request.GetEvaluateTaskDetailQuery) (*response.GetEvaluateTaskDetailResponse, error) {
	db := manage.DataBase.DB()

	// 查询评价任务基本信息
	var task dbModel.EvaluateTask
	if err := db.Where("id = ?", query.EvaluateTaskId).First(&task).Error; err != nil {
		if err.Error() == "record not found" {
			return nil, fmt.Errorf("评价任务不存在")
		}
		return nil, fmt.Errorf("查询评价任务失败: %v", err)
	}

	// 查询专家与评价任务关系记录
	var expertAndEvaluateTaskRelationshipList []dbModel.ExpertAndEvaluateTaskRelationship
	if err := db.Where("task_id = ?", query.EvaluateTaskId).Find(&expertAndEvaluateTaskRelationshipList).Error; err != nil {
		return nil, fmt.Errorf("查询专家关系记录失败: %v", err)
	}

	// 获取专家ID列表
	var expertIds []string
	for _, relationship := range expertAndEvaluateTaskRelationshipList {
		expertIds = append(expertIds, relationship.ExpertId)
	}

	// 查询专家用户信息
	var expertList []response.Expert
	if len(expertIds) > 0 {
		var users []dbModel.User
		if err := db.Where("id IN ?", expertIds).Find(&users).Error; err != nil {
			return nil, fmt.Errorf("查询专家用户信息失败: %v", err)
		}
		for _, user := range users {
			expertList = append(expertList, response.Expert{
				Id:       user.Id,
				Username: user.UserName,
				UserCode: user.UserCode,
			})
		}
	}

	// 构建响应数据
	responseData := &response.GetEvaluateTaskDetailResponse{
		Id:            task.Id,
		Name:          task.Name,
		Desc:          task.Desc,
		ResourceType:  task.ResourceType,
		ResourceId:    task.ResourceId,
		ResourceName:  task.ResourceName,
		TemplateId:    task.TemplateId,
		TemplateName:  task.TemplateName,
		PlanDuration:  task.PlanDuration,
		RealDuration:  task.RealDuration,
		StartTime:     formatTimePtr(task.StartTime),
		EndTime:       formatTimePtr(task.EndTime),
		LastStartTime: formatTimePtr(task.LastStartTime),
		ExecStatus:    task.ExecStatus,
		SegmentTime:   task.SegmentTime,
		ExpertList:    expertList,
		CreateTime:    task.CreateTime.Format("2006-01-02 15:04:05"),
		UpdateTime:    task.UpdateTime.Format("2006-01-02 15:04:05"),
	}

	return responseData, nil
}

// 更新评价任务状态
func (manage *EvaluateTaskManage) UpdateEvaluateTaskStatus(query *request.UpdateEvaluateTaskStatusQuery) error {
	if query.EvaluateTaskId == "" {
		return fmt.Errorf("评价任务ID不能为空")
	}

	if query.Time == "" {
		return fmt.Errorf("时间参数不能为空")
	}

	// 解析传入的时间，使用本地时区
	location, _ := time.LoadLocation("Local")
	currentTime, err := time.ParseInLocation("2006-01-02 15:04:05", query.Time, location)
	if err != nil {
		return fmt.Errorf("时间格式错误: %v", err)
	}

	fmt.Printf("===== 更新评价任务状态 =====\n")
	fmt.Printf("任务ID: %s\n", query.EvaluateTaskId)
	fmt.Printf("目标状态: %d\n", query.ExecStatus)
	fmt.Printf("传入时间: %s\n", query.Time)
	fmt.Printf("解析后时间: %s\n", currentTime.Format("2006-01-02 15:04:05"))
	fmt.Printf("解析后时间(Unix): %d\n", currentTime.Unix())
	fmt.Printf("解析后时间(时区): %s\n", currentTime.Location())

	db := manage.DataBase.DB()

	// 首先查询当前任务的状态和时间信息
	var currentTask dbModel.EvaluateTask
	if err := db.Where("id = ?", query.EvaluateTaskId).First(&currentTask).Error; err != nil {
		if err.Error() == "record not found" {
			return fmt.Errorf("评价任务不存在")
		}
		return fmt.Errorf("查询评价任务失败: %v", err)
	}

	fmt.Printf("当前任务状态: %d\n", currentTask.ExecStatus)
	fmt.Printf("当前RealDuration: %d秒\n", currentTask.RealDuration)
	fmt.Printf("计划时长PlanDuration: %d秒\n", currentTask.PlanDuration)
	if currentTask.StartTime != nil {
		fmt.Printf("StartTime: %s (Unix: %d, 时区: %s)\n",
			currentTask.StartTime.Format("2006-01-02 15:04:05"),
			currentTask.StartTime.Unix(),
			currentTask.StartTime.Location())
	} else {
		fmt.Println("StartTime: 未设置")
	}
	if currentTask.LastStartTime != nil {
		fmt.Printf("LastStartTime: %s (Unix: %d, 时区: %s)\n",
			currentTask.LastStartTime.Format("2006-01-02 15:04:05"),
			currentTask.LastStartTime.Unix(),
			currentTask.LastStartTime.Location())
	} else {
		fmt.Println("LastStartTime: 未设置")
	}
	if currentTask.EndTime != nil {
		fmt.Printf("EndTime: %s (Unix: %d, 时区: %s)\n",
			currentTask.EndTime.Format("2006-01-02 15:04:05"),
			currentTask.EndTime.Unix(),
			currentTask.EndTime.Location())
	} else {
		fmt.Println("EndTime: 未设置")
	}

	// 检查是否需要自动终止任务（达到计划时长）
	fmt.Printf("=== 检查是否需要自动终止任务 ===\n")
	if currentTask.PlanDuration > 0 && currentTask.ExecStatus != 3 { // 计划时长大于0且任务未终止
		var currentRealDuration int = currentTask.RealDuration
		
		// 如果当前状态是进行中，需要加上从LastStartTime到现在的时间
		if currentTask.ExecStatus == 1 && currentTask.LastStartTime != nil {
			durationFromLastStart := int(currentTime.Sub(*currentTask.LastStartTime).Seconds())
			if durationFromLastStart > 0 {
				currentRealDuration += durationFromLastStart
				fmt.Printf("当前状态为进行中，从LastStartTime到现在增加了%d秒\n", durationFromLastStart)
			}
		}
		
		fmt.Printf("当前总执行时长: %d秒, 计划时长: %d秒\n", currentRealDuration, currentTask.PlanDuration)
		
		// 如果达到或超过计划时长，自动终止任务
		if currentRealDuration >= currentTask.PlanDuration {
			fmt.Printf("⚠️ 任务达到计划时长，自动终止任务！\n")
			fmt.Printf("原始请求状态: %d -> 自动修改为终止状态: 3\n", query.ExecStatus)
			query.ExecStatus = 3 // 自动设置为终止状态
		} else {
			remainingTime := currentTask.PlanDuration - currentRealDuration
			fmt.Printf("任务未达到计划时长，剩余时间: %d秒\n", remainingTime)
		}
	} else if currentTask.PlanDuration <= 0 {
		fmt.Println("计划时长未设置或为0，跳过自动终止检查")
	} else {
		fmt.Println("任务已终止，跳过自动终止检查")
	}
	fmt.Printf("最终执行状态: %d\n", query.ExecStatus)

	// 准备更新的数据
	updateData := map[string]interface{}{
		"exec_status": query.ExecStatus,
	}

	// 根据不同的状态执行相应的逻辑
	switch query.ExecStatus {
	case 1: // 开始评价
		fmt.Printf("=== 开始评价时间设置 ===\n")
		// StartTime如果已经有值就不更新，没有值就设置为当前时间
		if currentTask.StartTime == nil {
			updateData["start_time"] = &currentTime
			fmt.Printf("开始评价: 设置StartTime=%s (Unix: %d)\n",
				currentTime.Format("2006-01-02 15:04:05"),
				currentTime.Unix())
		} else {
			fmt.Printf("开始评价: StartTime已存在=%s (Unix: %d)，不更新\n",
				currentTask.StartTime.Format("2006-01-02 15:04:05"),
				currentTask.StartTime.Unix())
		}
		// LastStartTime每次都更新
		updateData["last_start_time"] = &currentTime
		fmt.Printf("开始评价: 更新LastStartTime=%s (Unix: %d)\n",
			currentTime.Format("2006-01-02 15:04:05"),
			currentTime.Unix())

	case 2: // 暂停评价
		// 根据传入的Time和LastStartTime的差值累加到RealDuration中
		if currentTask.LastStartTime != nil {
			fmt.Printf("=== 时间计算详情 ===\n")
			fmt.Printf("当前时间: %s (Unix: %d)\n", currentTime.Format("2006-01-02 15:04:05"), currentTime.Unix())
			fmt.Printf("开始时间: %s (Unix: %d)\n", currentTask.LastStartTime.Format("2006-01-02 15:04:05"), currentTask.LastStartTime.Unix())

			// 计算时间差（秒）
			durationSeconds := currentTime.Sub(*currentTask.LastStartTime).Seconds()
			duration := int(durationSeconds)

			fmt.Printf("Unix时间差: %d - %d = %d\n", currentTime.Unix(), currentTask.LastStartTime.Unix(), currentTime.Unix()-currentTask.LastStartTime.Unix())
			fmt.Printf("计算的持续时间: %.2f秒 -> %d秒\n", durationSeconds, duration)

			// 确保时间差为正数（避免时间倒退的情况）
			if duration > 0 {
				newRealDuration := currentTask.RealDuration + duration
				updateData["real_duration"] = newRealDuration
				fmt.Printf("暂停评价: 本次持续时间=%d秒, 累计时长=%d秒\n", duration, newRealDuration)
			} else {
				fmt.Printf("警告: 暂停时间计算出现负值，跳过时长累加. 当前时间=%s, 上次开始时间=%s\n",
					currentTime.Format("2006-01-02 15:04:05"),
					currentTask.LastStartTime.Format("2006-01-02 15:04:05"))
			}
		} else {
			fmt.Println("警告: LastStartTime为空，无法计算暂停时的时长")
		}

	case 3: // 终止评价
		// 记录EndTime
		updateData["end_time"] = &currentTime
		// 只有在之前的状态是1的情况下，才根据传入的Time和LastStartTime的差值累加到RealDuration中
		if currentTask.ExecStatus == 1 && currentTask.LastStartTime != nil {
			fmt.Printf("=== 时间计算详情 ===\n")
			fmt.Printf("当前时间: %s (Unix: %d)\n", currentTime.Format("2006-01-02 15:04:05"), currentTime.Unix())
			fmt.Printf("开始时间: %s (Unix: %d)\n", currentTask.LastStartTime.Format("2006-01-02 15:04:05"), currentTask.LastStartTime.Unix())

			// 计算时间差（秒）
			durationSeconds := currentTime.Sub(*currentTask.LastStartTime).Seconds()
			duration := int(durationSeconds)

			fmt.Printf("Unix时间差: %d - %d = %d\n", currentTime.Unix(), currentTask.LastStartTime.Unix(), currentTime.Unix()-currentTask.LastStartTime.Unix())
			fmt.Printf("计算的持续时间: %.2f秒 -> %d秒\n", durationSeconds, duration)

			// 确保时间差为正数（避免时间倒退的情况）
			if duration > 0 {
				newRealDuration := currentTask.RealDuration + duration
				updateData["real_duration"] = newRealDuration
				fmt.Printf("终止评价: 本次持续时间=%d秒, 最终累计时长=%d秒\n", duration, newRealDuration)
			} else {
				fmt.Printf("警告: 终止时间计算出现负值，跳过时长累加. 当前时间=%s, 上次开始时间=%s\n",
					currentTime.Format("2006-01-02 15:04:05"),
					currentTask.LastStartTime.Format("2006-01-02 15:04:05"))
			}
		} else if currentTask.ExecStatus != 1 {
			fmt.Printf("终止评价: 之前状态不是进行中(%d)，不累加时长\n", currentTask.ExecStatus)
		} else {
			fmt.Println("警告: LastStartTime为空，无法计算终止时的时长")
		}
	}

	// 执行更新操作
	result := db.Model(&dbModel.EvaluateTask{}).
		Where("id = ?", query.EvaluateTaskId).
		Updates(updateData)

	// 检查数据库操作错误
	if result.Error != nil {
		return fmt.Errorf("更新数据库失败: %v", result.Error)
	}

	if result.RowsAffected == 0 {
		return fmt.Errorf("更新失败，未找到ID为 %s 的评价任务", query.EvaluateTaskId)
	}

	fmt.Printf("===== 状态更新完成 =====\n")
	fmt.Printf("受影响行数: %d\n", result.RowsAffected)

	// 根据更新后的状态管理监控和倒计时
	if query.ExecStatus == 1 && currentTask.PlanDuration > 0 {
		// 状态更新为进行中且有计划时长，启动监控，停止倒计时
		manage.startTaskMonitor(query.EvaluateTaskId)
		manage.stopFinalScoreCountdown(query.EvaluateTaskId)
	} else if query.ExecStatus == 2 {
		// 状态更新为暂停，停止监控和倒计时（暂停期间不计时）
		manage.stopTaskMonitor(query.EvaluateTaskId)
		manage.stopFinalScoreCountdown(query.EvaluateTaskId)
	} else if query.ExecStatus == 3 {
		// 状态更新为终止，停止监控并启动倒计时
		manage.stopTaskMonitor(query.EvaluateTaskId)
		// 启动6分钟倒计时
		manage.startFinalScoreCountdown(query.EvaluateTaskId)
	}

	fmt.Printf("监控管理完成\n\n")

	return nil
}

// 获取评价结果
func (manage *EvaluateTaskManage) GetEvaluateResult(query *request.GetEvaluateResultQuery) ([]response.GetEvaluateResultResponse, error) {
	db := manage.DataBase.DB()

	// 如果有expertId，查询EvaluateResult表返回该专家的结果
	if query.ExpertId != "" {
		tx := db.Model(&dbModel.EvaluateResult{})
		tx = tx.Where("task_id = ? AND expert_id = ?", query.EvaluateTaskId, query.ExpertId)

		// 根据任务ID查询评价结果
		var evaluateResults []dbModel.EvaluateResult
		if err := tx.Order("quota_id ASC, expert_id ASC").Find(&evaluateResults).Error; err != nil {
			return nil, fmt.Errorf("查询评价结果失败: %v", err)
		}

		// 转换为响应格式
		var responseList []response.GetEvaluateResultResponse
		for _, result := range evaluateResults {
			responseItem := response.GetEvaluateResultResponse{
				Id:            result.Id,
				TemplateId:    result.TemplateId,
				QuotaId:       result.QuotaId,
				QuotaName:     result.QuotaName,
				ExpertId:      result.ExpertId,
				AverageScore:  result.AverageScore,
				AbsoluteScore: result.AbsoluteScore,
				SegmentScore:  result.SegmentScore,
				MedianScore:   result.AverageScore, // 单个专家结果，中位数就是自己的分数
				StandardDeviationScore: 0, // 单个专家结果，标准差为0
				IsTotalScore:  result.IsTotalScore,
				Note:          result.Note,
				EvaluatePerson: result.EvaluatePerson,
			}
			responseList = append(responseList, responseItem)
		}
		return responseList, nil
	}

	// 如果没有expertId，直接查询EvaluateTotalResult表返回汇总结果
	fmt.Printf("📊 查询任务汇总评价结果，任务ID: %s\n", query.EvaluateTaskId)
	
	var totalResults []dbModel.EvaluateTotalResult
	if err := db.Where("task_id = ?", query.EvaluateTaskId).Order("quota_id ASC").Find(&totalResults).Error; err != nil {
		return nil, fmt.Errorf("查询汇总评价结果失败: %v", err)
	}

	fmt.Printf("🎯 找到 %d 条指标汇总结果\n", len(totalResults))

	// 转换为响应格式
	var responseList []response.GetEvaluateResultResponse
	var totalScore float64
	for _, result := range totalResults {
		responseItem := response.GetEvaluateResultResponse{
			Id:            result.Id,
			TemplateId:    result.TemplateId,
			QuotaId:       result.QuotaId,
			QuotaName:     result.QuotaName,
			ExpertId:      "", // 汇总结果不关联具体专家
			AverageScore:  result.AverageScore,
			AbsoluteScore: result.AbsoluteScore,
			MedianScore:   result.MedianScore,
			StandardDeviationScore: result.StandardDeviationScore,
			SegmentScore:  "", // 汇总结果没有分段评分
			IsTotalScore:  false, // 这里是指标汇总，不是专家总分
			Note:          "", // 汇总结果没有备注
			EvaluatePerson: "",
		}
		responseList = append(responseList, responseItem)

		totalScore += result.AbsoluteScore
		
		fmt.Printf("指标 %s: 平均分=%.2f, 中位分=%.2f, 标准差=%.2f, 绝对分=%.2f\n",
			result.QuotaName, result.AverageScore, result.MedianScore, result.StandardDeviationScore, result.AbsoluteScore)
	}
	responseList = append(responseList, response.GetEvaluateResultResponse{
		Id:            "",
		TemplateId:    "",
		QuotaId:       "",
		QuotaName:     "总分",
		ExpertId:      "",
		AverageScore:  0,
		AbsoluteScore: totalScore,
		MedianScore:   0,
		StandardDeviationScore: 0,
		SegmentScore:  "",
		IsTotalScore:  true,
		Note:          "",
		EvaluatePerson: "",
	})

	return responseList, nil
}

// 添加或修改评价结果
func (manage *EvaluateTaskManage) AddOrUpdateEvaluateResult(query *request.AddOrUpdateEvaluateResultQuery) error {
	if len(query.EvaluateResultList) == 0 {
		return nil
	}

	db := manage.DataBase.DB()
	// 获取模板信息
	var template dbModel.Template
	if err := db.Where("id = ?", query.TemplateId).First(&template).Error; err != nil {
		return fmt.Errorf("查询模板失败: %v", err)
	}

	// 获取当前模板所有指标
	var quotaList []dbModel.Quota
	quotaIdsMap := make(map[string]dbModel.Quota)
	if err := db.Where("template_id = ?", query.TemplateId).Find(&quotaList).Error; err != nil {
		return fmt.Errorf("查询指标失败: %v", err)
	}
	for _, quota := range quotaList {
		quotaIdsMap[quota.Id] = quota
	}

	// 开启事务确保数据一致性
	tx := db.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()

	// 先删除该用户对当前任务的所有评价结果
	if err := tx.Where("task_id = ? AND expert_id = ?", query.EvaluateTaskId, query.ExpertId).Delete(&dbModel.EvaluateResult{}).Error; err != nil {
		tx.Rollback()
		return fmt.Errorf("删除原有评价结果失败: %v", err)
	}

	// 批量创建新的评价结果
	var evaluateResults []dbModel.EvaluateResult
	for _, result := range query.EvaluateResultList {
		var absoluteScore float64 = 0
		quota, ok := quotaIdsMap[result.QuotaId]
		if !ok {
			absoluteScore = 0
		} else {
			if quota.EvaluationScore != nil {
				absoluteScore = float64(*quota.EvaluationScore) * result.AverageScore / 10
			}
		}
		evaluateResult := dbModel.EvaluateResult{
			Id:            commUtils.GenUUID(),
			TaskId:        query.EvaluateTaskId,
			TemplateId:    query.TemplateId,
			QuotaId:       result.QuotaId,
			QuotaName:     result.QuotaName,
			ExpertId:      query.ExpertId,
			AverageScore:  result.AverageScore,
			AbsoluteScore: absoluteScore,
			SegmentScore:  result.SegmentScore,
			IsTotalScore:  result.IsTotalScore,
		}
		evaluateResults = append(evaluateResults, evaluateResult)
	}

	// 批量插入评价结果
	if len(evaluateResults) > 0 {
		if err := tx.CreateInBatches(evaluateResults, 100).Error; err != nil {
			tx.Rollback()
			return fmt.Errorf("创建评价结果失败: %v", err)
		}
	}

	// 计算当前专家总体评价结果
	var totalAverageScore float64 = 0
	var totalAbsoluteScore float64 = 0
	for _, result := range evaluateResults {
		totalAverageScore += result.AverageScore
		totalAbsoluteScore += result.AbsoluteScore
	}

	// 添加总体评价结果
	if len(evaluateResults) > 0 {
		totalEvaluateResult := dbModel.EvaluateResult{
			Id:            commUtils.GenUUID(),
			TaskId:        query.EvaluateTaskId,
			TemplateId:    query.TemplateId,
			QuotaId:       "", // 总体评价结果不关联具体指标
			QuotaName:     "总体评价",
			ExpertId:      query.ExpertId,
			AverageScore:         totalAverageScore,
			AbsoluteScore: totalAbsoluteScore,
			SegmentScore:  "",
			IsTotalScore:  true, // 标识为总体评价结果
			Note:          query.Note,
			EvaluatePerson: query.EvaluatePerson,
		}

		// 插入总体评价结果
		if err := tx.Create(&totalEvaluateResult).Error; err != nil {
			tx.Rollback()
			return fmt.Errorf("创建总体评价结果失败: %v", err)
		}
	}

	// 重新计算任务指标统计结果
	fmt.Printf("===== 开始计算指标统计结果 =====\n")
	if err := manage.recalculateTaskTotalResults(tx, query.EvaluateTaskId, query.TemplateId); err != nil {
		tx.Rollback()
		return fmt.Errorf("计算指标统计结果失败: %v", err)
	}
	fmt.Printf("===== 指标统计结果计算完成 =====\n")

	// 提交事务
	if err := tx.Commit().Error; err != nil {
		return fmt.Errorf("提交事务失败: %v", err)
	}

	return nil
}
